package com.tianya.forum.controller;

import com.tianya.forum.common.AppResult;
import com.tianya.forum.common.ResultCode;
import com.tianya.forum.config.AppConfig;
import com.tianya.forum.exception.ApplicationException;
import com.tianya.forum.model.User;
import com.tianya.forum.services.IUserService;
import com.tianya.forum.utils.MD5Utils;
import com.tianya.forum.utils.StringUtil;
import com.tianya.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Slf4j
@Api(tags = "用户接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    /**
     * 注册接口
     * @param username 用户名
     * @param password 密码
     * @return 注册成功
     */
    @ApiOperation(value = "注册接口")
    @PostMapping("/register")
    public AppResult register(@ApiParam(value = "用户名") @RequestParam(value = "username") @NonNull String username,
                              @ApiParam(value = "昵称") @RequestParam(value = "nickname") @NonNull String nickname,
                              @ApiParam(value = "密码") @RequestParam(value = "password") @NonNull String password,
                              @ApiParam(value = "确认密码") @RequestParam(value = "passwordRepeat") @NonNull String passwordRepeat){

        //设置用户基本信息
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //校验密码和确认密码是否相等
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            throw new ApplicationException(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
        }
        //设置密码,盐
        String salt = UUIDUtil.UUID_32();
        String miwen = MD5Utils.md5Salt(password,salt);
        user.setSalt(salt);
        user.setPassword(miwen);
        //调用service层
        userService.createNormalUser(user);
        //返回
        return AppResult.success();
    }

    /**
     * 登录接口
     * @param username 用户名
     * @param password  密码
     * @return 成功
     */
    @ApiOperation(value = "登录接口")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest httpServletRequest,
                           @ApiParam(value = "用户名") @RequestParam(value = "username") @NonNull String username,
                           @ApiParam(value = "密码") @RequestParam(value = "password") @NonNull String password){
        //用户登录
        User user = userService.login(username, password);
        //获取session
        HttpSession session = httpServletRequest.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success();
    }

    /**
     * 获取用户详情
     * @param id 用户id
     * @return 用户信息
     */
    @ApiOperation(value = "获取用户详情")
    @GetMapping("info")
    public AppResult<User> getUserInfo(HttpServletRequest httpServletRequest,
                                 @ApiParam(value = "用户id") @RequestParam(value = "id", required = false) Long id){
        //根据id是否为空
        User user = null;
        //id为空，查询查询登录用户
        if(id == null){
            HttpSession session = httpServletRequest.getSession();
            //判断用户是否登录
            if(session == null || session.getAttribute(AppConfig.USER_SESSION) == null){
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else{
            //id不为空，查询指定用户
            user = userService.selectById(id);
        }
        //判断用户对象是否为空
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    /**
     * 退出登录接口
     * @return 成功
     */
    @ApiOperation(value = "退出接口")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        //注销session
        HttpSession session = request.getSession(false);
        if(session != null) {
            //表示用户在登录状态，销毁session
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    /**
     * 修改个⼈信息
     * @param username ⽤⼾名
     * @param nickname 昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNum 电话号
     * @param remark 个⼈简介
     * @return AppResult
     */
    @ApiOperation("修改个⼈信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("⽤⼾名") @RequestParam(value = "username",required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                @ApiParam("电话号") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @ApiParam("个⼈简介") @RequestParam(value = "remark",required = false) String remark){

        // 2. 对参数做⾮空校验（全部都为空，则返回错误描述）
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {
            // 返回错误信息
            return AppResult.failed("请输⼊要修改的内容");
        }
        // 从session中获取⽤⼾Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 3. 封装对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // ⽤⼾Id
        updateUser.setUsername(username); // ⽤⼾名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个⼈简介

        // 4. 调⽤Service中的⽅法
        userService.modifyInfo(updateUser);
        // 5. 查询最新的⽤⼾信息
        user = userService.selectById(user.getId());
        // 6. 把最新的⽤⼾信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 7. 返回结果
        return AppResult.success(user);

    }

    @PostMapping("/modifyPwd")
    @ApiOperation("修改密码")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码")
                                    @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码")
                                    @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码")
                                    @RequestParam("passwordRepeat") @NonNull String passwordRepeat){

        // 1. 校验新密码与确认密码是否相同
        if(!newPassword.equals(passwordRepeat)){
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 2. 获取当前登录的⽤⼾信息
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        // 3. 调⽤Service
        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        // 4. 销毁session
        if (session != null) {
            session.invalidate();
        }
        // 5. 返回结果
        return AppResult.success();



    }

}
